//
//  MLAShopFoodCommitOrderVC.m
//  MagicLampApp
//
//  Created by Zheng on 2019/4/8.
//  Copyright © 2019 zheng.magic.lamp.app. All rights reserved.
//

#import "MLAShopFoodCommitOrderVC.h"
#import "MLAShopFoodCommitOrderCell.h"
#import "MLABaseFieldModel.h"
#import "MLABaseFieldView.h"
#import "MLAShopFoodCommitOrderView.h"
#import "MLAWebVC.h"
#import "HXPayPlugin.h"
#import "MLAShopFoodOrderStatusVC.h"

@interface MLAShopFoodCommitOrderVC () <HXPayPluginDelegate>

@property (nonatomic, strong) MLAShopFoodCommitOrderView *bottomView;


@property (nonatomic, assign) NSString *payType;

@end

@implementation MLAShopFoodCommitOrderVC {
    NSArray<MLABaseFieldModel *> *modelsArr;
}

- (void)backAction {
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self configTitle:@"订单"];
 
    [self addSubviewsInView];
}

#pragma mark - Subviews
- (void)addSubviewsInView {
    
    _bottomView = [[MLAShopFoodCommitOrderView alloc] init];
    _bottomView.backgroundColor = [UIColor whiteColor];
    _bottomView.priceLbl.text = [NSString stringWithFormat:@"%.2f",_cartModel.total.doubleValue/100.];
    [_bottomView.buyBtn addTarget:self action:@selector(buyBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_bottomView];
    [_bottomView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(60);
    }];
    
    self.tableView.rowHeight = 90;    
    [self.tableView registerNib:[UINib nibWithNibName:@"MLAShopFoodCommitOrderCell" bundle:nil] forCellReuseIdentifier:@"kCellID"];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleView.mas_bottom);
        make.left.right.offset(0);
        make.bottom.offset(-60);
    }];
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, CX_GetScreenWidth(), 54);
    self.tableView.tableHeaderView = headerView;
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = [NSString stringWithFormat:@"%@(%@)",_shopName,_address];
    titleLbl.font = [UIFont systemFontOfSize:14];
    titleLbl.frame = CGRectMake(15, 0, 200, 54);
    [headerView addSubview:titleLbl];
    

    modelsArr = [self getModelsArr];
    CGFloat height = 300;
    
    UIView *footerView = [[UIView alloc] init];
//    footerView.backgroundColor = CX_GetColorHex(0xFCFCFC, 1);
    footerView.frame = CGRectMake(0, 0, CX_GetScreenWidth(), height);
    
    [modelsArr enumerateObjectsUsingBlock:^(MLABaseFieldModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        MLABaseFieldView *fieldView = [[MLABaseFieldView alloc] init];
        fieldView.tag = 12000+idx;
        fieldView.model = obj;
        [footerView addSubview:fieldView];
        if (idx == 0) {
            @weakify(self);
            fieldView.clickActionBlock = ^{
                @strongify(self);
                [self payTypeAction];
            };
        }
        
        if (idx == 0) {
            [fieldView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(20);
                make.left.right.equalTo(footerView);
                make.height.mas_equalTo(85);
            }];
        } else {
            [fieldView mas_makeConstraints:^(MASConstraintMaker *make) {
                UIView *view = [footerView viewWithTag:12000+idx-1];
                make.left.right.height.equalTo(view);
                make.top.equalTo(view.mas_bottom);
            }];
        }
    }];
    
    self.tableView.tableFooterView = footerView;

}

- (NSString *)getContentWithTag:(NSInteger)tag {
    MLABaseFieldView *fieldView = (MLABaseFieldView *)[self.tableView.tableFooterView viewWithTag:tag];
    return fieldView.inputText;
}

- (NSArray<MLABaseFieldModel *> *)getModelsArr {
    
    NSArray *infosArr = @[CX_GetFieldInfoDic(@"付款方式：", @"支付方式", @"30", @"0", @"0", @"1", @""),
                          CX_GetFieldInfoDic(@"备注：", @"输入备注", @"30", @"0", @"1", @"0", @""),
                          CX_GetFieldInfoDic(@"收货地址：", @"输入收货地址", @"40", @"0", @"1", @"0", @"")];
    return [[MLABaseFieldModel mj_objectArrayWithKeyValuesArray:infosArr] copy];
}

#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _cartModel.lists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MLAShopFoodCommitOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"kCellID" forIndexPath:indexPath];
    cell.model = _cartModel.lists[indexPath.row];
    return cell;
}


#pragma mark - Actions
- (void)payTypeAction {
#pragma mark 选择支付类型
    
    MLABaseFieldView *txfView = [self.view viewWithTag:12000];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"支付类型" message:@"选择您要支付的类型" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"线上支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.payType = @"1";
        txfView.inputText = @"线上支付";
    }];
    
    UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"货到付款" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.payType = @"2";
        txfView.inputText = @"货到付款";
    }];
    
    UIAlertAction *act3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:act1];
    [alert addAction:act2];
    [alert addAction:act3];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];

}


- (void)buyBtnAction {
#pragma mark 结算
    
    NSString *content = [self getContentWithTag:12001];
    NSString *address = [self getContentWithTag:12002];

    if (!self.payType) {
        [MLAHudManage showMessage:@"请选择支付方式"];
        return;
    }
    
    if (address.length == 0) {
        [MLAHudManage showMessage:@"请输入收货地址"];
        return;
    }
    
    if (content.length == 0) {
        content = @"";
    }
    
    NSDictionary *params = @{@"shop_id":_shopId,
                             @"address":address,
                             @"content":content,
                             @"pay_type":self.payType};
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kShopOrderAdd params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        if (self.payType.integerValue == 1) {
            NSString *order_number = response[@"lists"][@"order_id"];
            [self payBtnAction:order_number];
        } else {
            MLAShopFoodOrderStatusVC *statusVC = [[MLAShopFoodOrderStatusVC alloc] init];
            statusVC.isSuccess = YES;
            [self.navigationController pushViewController:statusVC animated:YES];
        }
    } failure:^{
        MLAShopFoodOrderStatusVC *statusVC = [[MLAShopFoodOrderStatusVC alloc] init];
        statusVC.isSuccess = NO;
        [self.navigationController pushViewController:statusVC animated:YES];
    }];
    
}

#pragma mark 支付
- (void)payBtnAction:(NSString *)orderNumber {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"支付类型" message:@"选择您要支付的类型" preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *act1 = [UIAlertAction actionWithTitle:@"农行支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self getPayUrl:@"A" withOrderId:orderNumber];
    }];
    
    UIAlertAction *act2 = [UIAlertAction actionWithTitle:@"邢台银行支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self payXingtai:orderNumber];
    }];
    
    
    UIAlertAction *act3 = [UIAlertAction actionWithTitle:@"其他银行支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self getPayUrl:@"6" withOrderId:orderNumber];
    }];
    
    UIAlertAction *act4 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:act1];
    [alert addAction:act2];
    [alert addAction:act3];
    [alert addAction:act4];
    
    [self.navigationController presentViewController:alert animated:YES completion:nil];
    
}

- (void)getPayUrl:(NSString *)paymentType withOrderId:(NSString *)orderId {
    
    NSDictionary *param = @{@"id":orderId,
                            @"text":@"",
                            @"type":@"1",
                            @"PaymentLinkType":@"2",
                            @"PaymentType":paymentType
                            };
    
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kPayAbcPay params:param success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        NSString *urlStr = response;
        MLAWebVC *webVC = [[MLAWebVC alloc] init];
        webVC.urlStr = urlStr;
        webVC.titleStr = @"支付页面";
        [self.navigationController pushViewController:webVC animated:YES];
    } failure:^{
        MLAShopFoodOrderStatusVC *statusVC = [[MLAShopFoodOrderStatusVC alloc] init];
        statusVC.isSuccess = NO;
        [self.navigationController pushViewController:statusVC animated:YES];
    }];
    
}

- (void)payXingtai:(NSString *)orderNumber {
    
    [MLAHttpManage postHostType:MLAHttpHostType_Diancan api:kPayXtPay params:@{@"order_sn":orderNumber} success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        NSString *oNo = response[@"transaction_id"];
        @weakify(self);
        dispatch_async(dispatch_get_main_queue(), ^{
            @strongify(self);
            
            __block MLAShopFoodCommitOrderVC *blockSelf = self;
            
            [HXPayPlugin startPayWithOrderSerialNumber:[NSString stringWithFormat:@"%@",oNo]
                                       andReqCommonURL:@"https://epay.xtbank.com/wscommon/ESB/UXUNDBF/UXUNCOMMONFRONT/common"//请求路径可不传
                                      andEncryptingKey:kCryptingKey//固定加密宏
                                       andEncryptingIv:kCryptingIv     /*固定加密宏*/                              andReqModeType:@"01"//固定参数
                                           andBankName:@""//银行名，可不传
                                       andPayTitleName:@""//支付方式，可不传
                                         andMemberUuid:@""//设备uuid，可不传
                                          andPointRate:@"0"//传0为生产，其他为测试
                                      andMemberphoneNo:@"10000000"//会员电话号码，可不传
                                          andNotifyTag:@""
                                        andpayTypeCode:@"1" andTransChannel:@"012" andAppID:@"" andMemberNo:@"" andCrossMemberNo:@"" andpayViewController:blockSelf andDelegate:blockSelf];
        });

    } failure:^{
        
    }];
    
    return;
    
}

- (void)HXPayPluginResult:(NSString *)resultStr {
    
}

@end
